package net.guerlab.smart.uploader.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.uploader.api.UploadApi;
import net.guerlab.smart.uploader.api.feign.FeignUploadApi;
import net.guerlab.spring.upload.entity.FileInfo;
import net.guerlab.spring.upload.entity.IFileInfo;
import net.guerlab.web.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;

/**
 * @author guer
 */
@Configuration
public class UploadApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(UploadApi.class)
    public UploadApi uploadApiFeignWrapper(FeignUploadApi api) {
        return new UploadApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class UploadApiFeignWrapper implements UploadApi {

        private FeignUploadApi api;

        private static String toBase64(MultipartFile file) {
            try {
                String contentType = file.getContentType();
                String contentBase64 = Base64.getEncoder().encodeToString(file.getBytes());
                return "data:" + contentType + ";base64," + contentBase64;
            } catch (Exception e) {
                throw new ApplicationException(e.getLocalizedMessage(), e);
            }
        }

        @Override
        public IFileInfo single(MultipartFile file, String path) {
            return base64Single(toBase64(file), path);
        }

        @Override
        public IFileInfo base64Single(String fileBase64, String path) {
            String savePath = StringUtils.trimToNull(path);
            Result<FileInfo> result =
                    savePath == null ? api.base64Single(fileBase64) : api.base64Single(fileBase64, path);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }
    }

}
